<template>
  <div class="vehicle-list-container">
    <div class="filter-container">
      <el-card>
        <h3>筛选条件</h3>
        <el-form :model="queryParams" inline>
          <el-form-item label="品牌">
            <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable></el-input>
          </el-form-item>
          <el-form-item label="型号">
            <el-input v-model="queryParams.model" placeholder="请输入型号" clearable></el-input>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number v-model="queryParams.minPrice" :min="0" placeholder="最低价"></el-input-number>
            <span class="price-separator">-</span>
            <el-input-number v-model="queryParams.maxPrice" :min="0" placeholder="最高价"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="vehicle-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="vehicle in vehicleList" :key="vehicle.id">
          <el-card class="vehicle-card" shadow="hover">
            <div class="vehicle-image">
              <img :src="getImageUrl(vehicle.imageUrl)" alt="车辆图片" @error="handleImageError">
            </div>
            <div class="vehicle-info">
              <h3>{{ vehicle.brand }} {{ vehicle.model }}</h3>
              <p>车牌号: {{ vehicle.plateNumber }}</p>
              <p>颜色: {{ vehicle.color }}</p>
              <p>座位数: {{ vehicle.seatCount }}</p>
              <div class="vehicle-price">
                ¥ {{ vehicle.dailyPrice }} <span>/ 天</span>
              </div>
              <el-button type="primary" @click="viewDetail(vehicle.id)">查看详情</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :page-sizes="[8, 16, 24, 32]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listVehicles } from '@/api/vehicle'

const router = useRouter()
const loading = ref(false)
const vehicleList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 8,
  brand: '',
  model: '',
  minPrice: null,
  maxPrice: null
})

// 图片URL处理函数
const getImageUrl = (url) => {
  if (!url) return '/assets/no-image.png';
  
  // 如果是绝对URL（以http开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // 如果是placeholder站点且有连接问题，使用本地占位图
    if (url.includes('via.placeholder.com')) {
      return '/assets/no-image.png';
    }
    return url;
  }
  
  // 如果是相对URL，需要检查格式并调整
  
  // 1. 修正端口问题：从3000改为8081
  if (url.includes('localhost:3000')) {
    url = url.replace('localhost:3000', 'localhost:8081');
  }
  
  // 2. 如果URL不以/开头，添加/
  if (!url.startsWith('/')) {
    url = '/' + url;
  }
  
  // 拼接服务器地址，使用正确的端口8081
  const host = window.location.protocol + '//' + window.location.hostname + ':8081';
  return host + url;
}

// 图片加载错误处理
const handleImageError = (e) => {
  if (e && e.target) {
    // 使用本地资源文件夹中的占位图
    e.target.src = '/assets/no-image.png';
  }
}

// 获取车辆列表
const getVehicleList = async () => {
  loading.value = true
  try {
    const res = await listVehicles(queryParams)
    vehicleList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取车辆列表失败:', error)
    ElMessage.error('获取车辆列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/vehicle/${id}`)
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getVehicleList()
}

// 重置查询
const resetQuery = () => {
  queryParams.brand = ''
  queryParams.model = ''
  queryParams.minPrice = null
  queryParams.maxPrice = null
  handleSearch()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getVehicleList()
}

// 每页条数变化
const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  getVehicleList()
}

// 组件挂载时获取数据
onMounted(() => {
  getVehicleList()
})
</script>

<style scoped>
.vehicle-list-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.price-separator {
  margin: 0 10px;
}

.vehicle-list {
  margin-bottom: 20px;
}

.vehicle-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.vehicle-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.vehicle-image {
  height: 200px;
  overflow: hidden;
  margin-bottom: 10px;
}

.vehicle-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.vehicle-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.vehicle-price {
  font-size: 20px;
  color: #f56c6c;
  margin: 10px 0 15px;
  font-weight: bold;
}

.vehicle-price span {
  font-size: 14px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 